import React, { memo } from 'react'
import {
  changeMessageAction,
  decrementAction,
  incrementAction,
} from './store/module/counter'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'

const Home = memo((props) => {
  console.log('home渲染')
  // 只要state改变了，就会重新渲染
  const { message } = useSelector(
    (state) => ({
      message: state.counter.message,
    }),
    shallowEqual
  )

  const dispatch = useDispatch()
  function changeMessage() {
    dispatch(changeMessageAction('acd'))
  }

  return (
    <div>
      <h2>Hello: {message}</h2>
      <button onClick={changeMessage}>修改message</button>
    </div>
  )
})

const App = memo(function (props) {
  console.log('app渲染')
  const { counter } = useSelector(
    (state) => ({
      counter: state.counter.counter,
    }),
    shallowEqual
  )

  const dispatch = useDispatch()
  function incrementHandle() {
    dispatch(incrementAction())
  }

  function decrementHandle() {
    dispatch(decrementAction())
  }

  return (
    <div>
      <h2>App Page</h2>
      <h3>counter: {counter}</h3>
      <button onClick={incrementHandle}>+1</button>
      <button onClick={decrementHandle}>-1</button>
      <Home />
    </div>
  )
})

export default App
